﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Net.Sockets;
using System.Threading;

namespace WPFConsole
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// 

    public partial class PConsole
    {
        byte[] Buffer { get; set; }

        Socket _sck;

        delegate void CommandAction();
        delegate void ProtocolAction(List<string> toks);
        delegate void CmdArgsActions(string[] args);

        readonly Dictionary<string, CommandAction> _commands = new Dictionary<string, CommandAction>();
        readonly Dictionary<string, ProtocolAction> _numerics = new Dictionary<string, ProtocolAction>();
        readonly Dictionary<string, CmdArgsActions> _cmdArgs = new Dictionary<string, CmdArgsActions>();

        //WMPLib.WindowsMediaPlayer bgmusic = new WMPLib.WindowsMediaPlayer();

        bool _connected;

        bool _needToStopParsingArgs;

        string _worldConsoleBackup = "";

        Thread _listener;

        readonly List<string> _inputBuffer = new List<string>();
        int _cNumb;

        public PConsole()
        {
            InitializeComponent();
            _connected = false;

            //Add the client side commands
            _commands.Add("connect", ConnectCommand);
            _commands.Add("help", HelpCommand);
            _commands.Add("disconnect", DisconnectCommand);
            _commands.Add("ping", PingCommand);
            _commands.Add("clear", ClearCommand);

            //Add the server protocols
            _numerics.Add("0", WorldProtocol);
            _numerics.Add("1", ChatProtocol);
            _numerics.Add("2", InventoryProtocol);
            _numerics.Add("3", SoundProtocol);

            //Add command line arguments
            _cmdArgs.Add("-connect", ConnectCommand);
            _cmdArgs.Add("-login", LoginCommand);

        }

        private void rTitle_MouseDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        private void ClearInput()
        {
            if (tbInput.Dispatcher.Thread == Thread.CurrentThread)
            {
                tbInput.Text = "";
            }
            else
            {
                tbInput.Dispatcher.Invoke(new VoidMethod(ClearInput));
            }
            
        }

        delegate void VoidStringMethod(string text);
        delegate void VoidStringStringMethod(string user, string text);
        delegate void VoidMethod();

        public void WriteLine(string text)
        {
            if (tbConsole.Dispatcher.Thread == Thread.CurrentThread)
            {
                tbConsole.AppendText(text + Environment.NewLine);
                
                tbConsole.ScrollToEnd();
            }
            else
            {
                tbConsole.Dispatcher.Invoke(new VoidStringMethod(WriteLine), text);
            }
        }

        public void WriteLine(string user, string text)
        {
            if (tbChat.Dispatcher.Thread == Thread.CurrentThread)
            {
                tbChat.Text += '>' + user + ": " + text + Environment.NewLine;
                tbChat.ScrollToEnd();
            }
            else
            {
                tbChat.Dispatcher.Invoke(new VoidStringStringMethod(WriteLine), user, text);
            }
        }

        public string CurrentWorldText
        {
            get
            {
                return new TextRange(tbConsole.Document.ContentStart, tbConsole.Document.ContentEnd).Text;
            }
        }

        void SendToServer(string msg)
        {
            msg = msg.Trim();
            if (!_connected || string.IsNullOrWhiteSpace(msg)) return;
            byte[] data = Encoding.ASCII.GetBytes(msg);
            Array.Resize(ref data, _sck.SendBufferSize);
            _sck.Send(data);
        }

        public void PreMadeInput(string text)
        {
            List<string> tokens = text.Split(' ').ToList();
            tbInput.IsEnabled = false;
            tbInput.Text = text;
            if (tbChat.Dispatcher.Thread == Thread.CurrentThread)
            {
                if (_commands.ContainsKey(tokens[0].ToLower()))
                {
                    _commands[tokens[0].ToLower()]();
                }
                else if (_connected)
                {
                    SendToServer(text);
                    ClearInput();
                }
                else
                {
                    WriteLine(text);
                    ClearInput();
                }
            }
            else
            {
                tbChat.Dispatcher.Invoke(new VoidStringMethod(PreMadeInput), text);
            }
            tbInput.IsEnabled = true;
        }

        void Listen()
        {
            try
            {
                while (true)
                {

                    if (!_sck.Connected) { throw new SocketException(10054); }

                    Buffer = new byte[_sck.SendBufferSize];

                    int bytesRead = _sck.Receive(Buffer,_sck.SendBufferSize, SocketFlags.None);

                    if (bytesRead == 0)
                    {
                        _connected = false;
                        WriteLine("Server disconnected. Closing socket...");
                        _sck.Close();
                        WriteLine("Socket closed. Successfully disconnected from server.");
                    }


                    /** Format buffer to take care of whitespace or extra crap*/
                    List<byte> formatted = new List<byte>(bytesRead);
                    for (int i = 0; i < bytesRead; i++)
                    {
                        if (Buffer[i] != default(byte))
                        {
                            formatted.Add(Buffer[i]);
                        }
                    }

                    string strData = Encoding.ASCII.GetString(formatted.ToArray()).Trim();
                    if (string.IsNullOrWhiteSpace(strData)) continue;
                    List<string> toks = strData.Split(' ').ToList();
                    string protocol = toks[0];

                    if (_numerics.ContainsKey(protocol))
                    {
                        if (protocol != "2" && _worldConsoleBackup != "")
                        {
                            ClearCommand();
                            WriteLine(_worldConsoleBackup);
                            _worldConsoleBackup = "";
                        }
                        _numerics[protocol](toks);
                    }
                    else
                    {
                        WriteLine("Server sent erroneous protocol. Message was '"+strData+"'");
                    }
                }
            }
            catch (SocketException error)
            {
                WriteLine("Error: " + error.Message);
            }
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            string input = tbInput.Text;
            List<string> tokens = input.Split(' ').ToList();
            if (e.Key == Key.Enter)
            {
                if (_commands.ContainsKey(tokens[0].ToLower()))
                {
                    _commands[tokens[0].ToLower()]();
                }
                else if (_connected)
                {
                    SendToServer(input);
                    ClearInput();
                }
                else
                {
                    WriteLine(input);
                    ClearInput();
                }
                _inputBuffer.Add(input);
            }
            if (e.Key != Key.Up) return;
            tbInput.Text = _inputBuffer[_inputBuffer.Count - 1 + _cNumb];
            _cNumb++;
            WriteLine(_cNumb.ToString(CultureInfo.InvariantCulture));
        }

        private void eClose_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (_connected) _sck.Close();
            Close();
        }

        private void eMinimize_MouseDown(object sender, MouseButtonEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }

        private void MainWin_Loaded(object sender, RoutedEventArgs e)
        {
            string[] args = Environment.GetCommandLineArgs();
            foreach (string arg in args)
            {
                if (_cmdArgs.ContainsKey(arg) && !_needToStopParsingArgs)
                {
                    _cmdArgs[arg](args);
                }
            }
        }
    }
}
